using System;
using System.ComponentModel;
using System.Windows.Input;
using System.Windows;
using ErpManager.WPF.Models;

namespace ErpManager.WPF.ViewModels
{
    public class MainViewModel : INotifyPropertyChanged
    {
        private User _currentUser;
        private int _selectedMenuIndex;
        private object _currentView;

        public event PropertyChangedEventHandler? PropertyChanged;

        public User CurrentUser
        {
            get => _currentUser;
            set
            {
                _currentUser = value;
                OnPropertyChanged(nameof(CurrentUser));
            }
        }

        public int SelectedMenuIndex
        {
            get => _selectedMenuIndex;
            set
            {
                _selectedMenuIndex = value;
                OnPropertyChanged(nameof(SelectedMenuIndex));
                UpdateCurrentView();
            }
        }

        public object CurrentView
        {
            get => _currentView;
            set
            {
                _currentView = value;
                OnPropertyChanged(nameof(CurrentView));
            }
        }

        public ICommand LogoutCommand { get; }

        public MainViewModel(User user)
        {
            _currentUser = user;
            LogoutCommand = new RelayCommand(Logout);
            SelectedMenuIndex = 0; // 默认选中产品管理
        }

        private void UpdateCurrentView()
        {
            switch (SelectedMenuIndex)
            {
                case 0:
                    CurrentView = new Views.ProductView();
                    break;
                case 1:
                    CurrentView = new Views.DealerView();
                    break;
                case 2:
                    CurrentView = new Views.OutboundView();
                    break;
                case 3:
                    CurrentView = new Views.LogView();
                    break;
            }
        }

        private void Logout()
        {
            var result = MessageBox.Show("确定要退出登录吗？", "确认", MessageBoxButton.YesNo, MessageBoxImage.Question);
            if (result == MessageBoxResult.Yes)
            {
                // 创建并显示登录窗口
                var loginWindow = new Views.LoginWindow();
                loginWindow.Show();

                // 关闭主窗口
                Application.Current.MainWindow.Close();
            }
        }

        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
